package com.example.xyr.myapplication.ui

import android.app.Activity
import android.content.Intent
import android.os.Environment
import android.util.DisplayMetrics
import android.view.View
import android.widget.LinearLayout
import android.widget.Toast
import cn.jpush.im.android.api.JMessageClient
import cn.jpush.im.android.api.model.UserInfo
import com.example.xyr.myapplication.Constant
import com.example.xyr.myapplication.MyApp
import com.example.xyr.myapplication.R
import com.example.xyr.myapplication.base.BaseActivity
import com.example.xyr.myapplication.myinterface.ActivityCallback
import com.example.xyr.myapplication.ui.im.ChatUserUtils
import com.example.xyr.myapplication.utils.*
import com.example.xyr.myapplication.utils.PootoAvatarUtils.hasSdcard
import com.jrmf360.walletlib.JrmfWalletClient
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.activity_my_user.*
import kotlinx.android.synthetic.main.pullzoom_background.*
import kotlinx.android.synthetic.main.pullzoom_head.*
import kotlinx.android.synthetic.main.pullzoom_item.*
import kotlinx.android.synthetic.main.titlebar_layout.*
import java.io.File


/**
 * Created by ylcf on 2018/8/30.
 */
class MyUserActivity : BaseActivity(), View.OnClickListener, ActivityCallback {

    private lateinit var pootoAvatarUtils: PootoAvatarUtils

    override fun getLayout(): Int = R.layout.activity_my_user

    override fun init() {
        val localDisplayMetrics = DisplayMetrics()
        windowManager.defaultDisplay.getMetrics(localDisplayMetrics)
        val mScreenWidth = localDisplayMetrics.widthPixels
        val localObject = LinearLayout.LayoutParams(mScreenWidth, (9.0f * (mScreenWidth / 16.0f)).toInt())
        user_pullzoom.setHeaderLayoutParams(localObject)
        pootoAvatarUtils = PootoAvatarUtils.getInstance(this)
    }

    override fun initListener() {
        my_user_iv_avatar.setOnClickListener(this)
        my_user_rl_modify.setOnClickListener(this)
        my_user_wallet.setOnClickListener(this)
        my_back_user.setOnClickListener(this)
        titleBar.ivBack.setOnClickListener(this)
        my_password.setOnClickListener(this)
    }


    override fun initDate(intent: MyIntent?) {
        BitmapUtils.getInstance().upDateUserInfo()
        titleBar.setTitle("我的设置")
        Picasso.with(this).load(R.drawable.my_user_bg).into(pullzoom_iv_bg)
        val together = DateUtils.getTogether("27-03-2018")
        //日期
        my_user_tv_together.text = String.format(getString(R.string.my_together), together)
        //昵称
        my_user_tv_name.text = BitmapUtils.getInstance().getmNickName()
        //用户ID
        user_tv_id.text = "ID:${BitmapUtils.getInstance().userId}"
        //头像
        if (BitmapUtils.getInstance().getmAvatar() != null) {
            my_user_iv_avatar.setImageBitmap(BitmapUtils.getInstance().getmAvatar())
        }
        //性别
        var gender = BitmapUtils.getInstance().gender
        when (gender) {
            UserInfo.Gender.female -> iv_gender.setImageResource(R.drawable.d_nvhaier)
            UserInfo.Gender.male -> iv_gender.setImageResource(R.drawable.d_nanhaier)
            else -> iv_gender.setImageResource(R.drawable.d_aoteman)
        }
    }


    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_back -> finish()
        //更换头像
            R.id.my_user_iv_avatar -> poputWin()
        //更改昵称
            R.id.my_user_rl_modify -> ModifyNameActivity.initActivity(this, Constant.REVISE_USER_NAME, ModifyNameActivity.Type.ModifyName)
        //进入钱包
            R.id.my_user_wallet -> {
                if (StringUtil.isNotEmpty(MyApp.token) && StringUtil.isNotEmpty(MyApp.userId))
                    JrmfWalletClient.intentWallet(this, MyApp.userId, MyApp.token, BitmapUtils.getInstance().getmNickName(), "")
            }
        //修改密码
            R.id.my_password -> ModifyNameActivity.initActivity(this, Constant.MODIFY_PASSWORD, ModifyNameActivity.Type.ModifyPassWord)
        //退出登录
            R.id.my_back_user -> {
                if (ActivityManger.instance.finishActivity(MainActivity::class.java)) {
                    startActivity(Intent(this, LoginActivity::class.java))
                    JMessageClient.logout()
                    finish()
                }
            }
        }
    }


    /**
     * 弹框选择头像方式
     */
    fun poputWin() {
        PoputWindowUtils.getInstance().showPopmenu(this, user_pullzoom) { type ->
            LogUtil.e("tag", "type = $type")
            if (type == PoputWindowUtils.Type.CAMERA) {
                pootoAvatarUtils.checkStoragePermission(this@MyUserActivity)
            } else if (type == PoputWindowUtils.Type.GALLERY) {
                pootoAvatarUtils.checkReadPermission(this@MyUserActivity)
            }
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        // 用户没有进行有效的设置操作，返回
        if (resultCode == Activity.RESULT_CANCELED) {
            Toast.makeText(application, "取消", Toast.LENGTH_LONG).show()
            return
        }

        when (requestCode) {
            PootoAvatarUtils.CODE_GALLERY_REQUEST -> pootoAvatarUtils.cropRawPhoto(data?.data)

            PootoAvatarUtils.CODE_CAMERA_REQUEST -> if (hasSdcard()) {
                val tempFile = File(
                        Environment.getExternalStorageDirectory(),
                        PootoAvatarUtils.IMAGE_FILE_NAME)
                //                    cropRawPhoto(Uri.fromFile(tempFile));
                pootoAvatarUtils.cropRawPhoto(pootoAvatarUtils.getImageContentUri(tempFile))
            } else {
                Toast.makeText(application, "没有SDCard!", Toast.LENGTH_LONG)
                        .show()
            }

            PootoAvatarUtils.CODE_RESULT_REQUEST -> {
                PoputWindowUtils.getInstance().dismissPopmenu()
                //更新头像
                val file = pootoAvatarUtils.setImage(my_user_iv_avatar)
                ChatUserUtils.upDataAvatar(this, file)
            }
        }
        super.onActivityResult(requestCode, resultCode, data)
    }


    override fun onActivityCallBack(requestCode: Int, resultCode: Int, data: Intent?) {
        // 用户没有进行有效的设置操作，返回
        if (resultCode == Activity.RESULT_CANCELED) {
            Toast.makeText(application, "取消", Toast.LENGTH_LONG).show()
            return
        }
        when (requestCode) {
        //更改昵称
            Constant.REVISE_USER_NAME -> {
                val nickName = data?.getStringExtra(Constant.NICK_NAME)
                val genderStr = data?.getStringExtra(Constant.GENDER)
                if (StringUtil.isNotEmpty(nickName)) {
                    ChatUserUtils.updateNickName(this, nickName)
                    var gender = if (genderStr == "boy") {
                        UserInfo.Gender.male
                    } else {
                        UserInfo.Gender.female
                    }
                    when (gender) {
                        UserInfo.Gender.female -> iv_gender.setImageResource(R.drawable.d_nvhaier)
                        UserInfo.Gender.male -> iv_gender.setImageResource(R.drawable.d_nanhaier)
                        else -> iv_gender.setImageResource(R.drawable.d_aoteman)
                    }
                    ChatUserUtils.updateGender(this, gender)
                    my_user_tv_name.text = nickName
                    BitmapUtils.getInstance().upDateUserInfo()
                }
            }
        }
    }

    override fun onDestroy() {
        my_user_iv_avatar.setImageBitmap(null)
        PoputWindowUtils.getInstance().destroy()
        super.onDestroy()
    }
}